package com.cirkana.viewer.share.twitter;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;

import com.cirkana.data.security.IUser;
import com.cirkana.data.security.IUserService;
import com.cirkana.viewer.share.IShareServiceProxy;
import com.cirkana.viewer.share.ShareServiceException;

public class TwitterProxy implements IShareServiceProxy {

	private static final String JTWITTER_OAUTH_KEY = "OEfL8LvCMeVLoITt6Nn9g";
	private static final String JTWITTER_OAUTH_SECRET = "qoAYqiQtCn2KR0CyZGKbwPqarGH2dbsRUtpBIGstw9U";

	private IUserService userService = null;
	private OAuthSignpostClient oauthClient = null;

	@Override
	public void setUser(IUser user) throws ShareServiceException {
		if (user.getUserServices() != null)
			if (user.getUserServices().containsKey(IShareServiceProxy.SHARE_SERVICE_TWITTER))
				this.userService = user.getUserServices().get(IShareServiceProxy.SHARE_SERVICE_TWITTER);
	}

	@Override
	public boolean hasAccess() {
		return (this.userService != null);
	}

	@Override
	public String[] resolveAccess(String serviceUser, String servicePassword) throws ShareServiceException {
		try {
			oauthClient = new OAuthSignpostClient(JTWITTER_OAUTH_KEY, JTWITTER_OAUTH_SECRET, "oob");
			oauthClient.setName(serviceUser);
			HttpClient client = new DefaultHttpClient();
			resolveAccess1(client, oauthClient.authorizeUrl().toString());
			return new String[] {};
		} catch (Exception e) {
			throw new ShareServiceException(e);
		}
	}

	protected void resolveAccess1(HttpClient client, String url) throws Exception {
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		response.getEntity().getContent();
	}

	@Override
	public void prepareAccess() throws ShareServiceException {
		String[] securityAccess = this.userService.getSecurityData();
		String requestToken = securityAccess[0];
		String requestSecret = securityAccess[1];
		this.oauthClient = new OAuthSignpostClient(JTWITTER_OAUTH_KEY, JTWITTER_OAUTH_SECRET, requestToken, requestSecret);
	}

	@Override
	public void sendMessage(String message) throws ShareServiceException {
		Twitter twitter = new Twitter(this.userService.getNickName(), this.oauthClient);
		twitter.setStatus(message);
	}

}
